package life.majiang.community.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import life.majiang.community.dto.AccessTokenDTO;
import life.majiang.community.dto.GitHubUser;
import life.majiang.community.provider.GitHubProvider;

@Controller
public class AuthorizeController {
	
	@Value("${github.client.id}")
	private String clientId;
	
	@Value("${github.client.secret}")
	private String clientSecret;
	
	@Value("${github.redirect.uri}")
	private String redirectUri;
	
	@Value("${github.identity.uri}")
	private String identityUri;
	
	@Autowired
	private GitHubProvider gitHubProvider;
	
	@GetMapping("/github/oauth")
	public String getCode(){
		return "redirect:" + identityUri +"?client_id=" + clientId + "&scope=user&state=1&redirect_uri=" + redirectUri;
	}
	
    @GetMapping("/callback")
	public String callback(String code, String state, HttpSession session){
    	AccessTokenDTO accessTokenDTO = new AccessTokenDTO();
    	accessTokenDTO.setClient_id(clientId);
    	accessTokenDTO.setClient_secret(clientSecret);
    	accessTokenDTO.setCode(code);
    	accessTokenDTO.setRedirect_uri(redirectUri);
    	accessTokenDTO.setState(state);
    	String accessToken = gitHubProvider.getAccessToken(accessTokenDTO);
    	// System.out.println("access_token = " + accessToken);
    	GitHubUser user = gitHubProvider.getUser(accessToken);
    	if (user != null) {
    		session.setAttribute("user", user);
    	} else {
    		
    	}
    	return "redirect:/";
    }
    
}
